//
//  VideoCapture.m
//  SQVideoCapture
//
//  Created by ToothBond on 2017/5/4.
//  Copyright © 2017年 rensq. All rights reserved.
//

#import "VideoCapture.h"
#import <AVFoundation/AVFoundation.h>
#import "H264Encoder.h"

@interface VideoCapture()<AVCaptureVideoDataOutputSampleBufferDelegate>

@property(nonatomic,weak)AVCaptureVideoPreviewLayer *preViewLayer;
@property(nonatomic,weak)AVCaptureSession *session;
@property(nonatomic,strong)H264Encoder *encoder;

@end


@implementation VideoCapture

- (void)startCapture:(UIView *)preView
{
    //准备编码
    self.encoder = [[H264Encoder alloc] init];
    [self.encoder prepareEncodeWithWidth:720 height:1280];
    
    
    //1.创建session
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPreset1280x720;
    self.session = session;
    
    //2.设置视频的输入
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error;
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    [session addInput:input];
    
    //3.设置视频的输出
    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    [output setSampleBufferDelegate:self queue:queue];
    [output setAlwaysDiscardsLateVideoFrames:YES];  //丢弃
    [session addOutput:output];
    
    //设置视频的方向 必须在 addOutput:方法之后
    AVCaptureConnection *connection = [output connectionWithMediaType:AVMediaTypeVideo];
    if (connection.isVideoOrientationSupported) {
        connection.videoOrientation = AVCaptureVideoOrientationPortrait;
    }else{
        NSLog(@"不支持设置方向");
    }
    
    //4.添加预览图层
    AVCaptureVideoPreviewLayer *layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    layer.frame = preView.bounds;
    [preView.layer insertSublayer:layer atIndex:0];
    self.preViewLayer = layer;
    
    //5.开始采集
    [session startRunning];
}

- (void)stopCapture
{
    [self.preViewLayer removeFromSuperlayer];
    [self.session stopRunning];
    [self.encoder endEncode];
}

#pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    NSLog(@"采集到视频画面");
    [self.encoder encodeFrame:sampleBuffer];
}

@end
